//
//  PushUMExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/15.
//

import Foundation
import SwiftUI
import UMCommon
import UMPush

class PushUMImpl: PushProtocol {
    
    func initSDK() {
        
    }
    
    func setAccount(account: String?) {
        Task{
            //设置账号，需要先清除别名，清除完成后在设置别名
            if !AppStorageManager.shared.pushAccount.isEmpty {
                try await clearsetAccount(pushId: AppStorageManager.shared.pushAccount)
            }
            //showLog("开始存储别名")
            await MainActor.run { //同步主线程
                var pushId = ""
                if (account ?? "").isEmpty {
                    //本地的
                    if AppStorageManager.shared.pushAccount.isEmpty {
                        //没有数据创建一个
                        pushId = UUID().uuidString
                    } else {
                        pushId = AppStorageManager.shared.pushAccount
                    }
                } else {
                    pushId = account ?? ""
                }
                AppStorageManager.shared.pushAccount = pushId //别名存储
            }
            try await setAccount2(pushId: AppStorageManager.shared.pushAccount)
        }
    }
    
    private func clearsetAccount(pushId: String) async throws   {
        try await withCheckedThrowingContinuation { continuation in
            DispatchQueue.main.async {
                //                showLog("开始清除别名")
                //别名有数据，先移除别名
                UMessage.removeAlias(pushId, type: "自定义类型") { responseObject, error in
                    if error == nil {
                        showLog("别名移除成功")
                        continuation.resume()
                    } else {
                        showLog("别名移除失败: \(error!.localizedDescription)")
                        continuation.resume()
                    }
                }
            }
        }
    }
    
    private func setAccount2(pushId: String) async throws {
        try await withCheckedThrowingContinuation { continuation in
            DispatchQueue.main.async {
                //                showLog("开始设置别名")
                // 调用友盟 SDK 设置别名
                UMessage.setAlias(pushId, type: "自定义类型") { responseObject, error in
                    if error == nil {
                        showLog("别名设置成功: \(String(describing: pushId))")
                        continuation.resume()
                    } else {
                        showLog("别名设置失败: \(error!.localizedDescription)")
                        continuation.resume()
                    }
                }
            }
        }
    }
    
    func getAccount() -> String {
        return AppStorageManager.shared.pushAccount
    }
    
    
    //发送定时任务，请求服务器保存
    func sendSchedule(taskName: String, msgId: String, title: String, content: String, time: Int64) async throws {
        if getAccount().isEmpty {
            return
        }
        let bean = PushSchedulesIOSBean(msgId: msgId, sign: "sign", title: title, content: content, alias: getAccount(), time: time)
        //这边要执行SM2加密，但是实在不行了，就不加密，android有加密
        try await _ = AiNetManager.shared.requestPush(jsonString: toJson(bean) ?? "", modeType: String.self)
        
        if BackupsManager.shared.backupsType != BackupsType.local {
            showLog("不是本地备份，需要发送android")
            let bean = PushSchedulesAndroidBean(msgId: msgId, sign: "sign", title: title, content: content, alias: getAccount(), time: time)
            //这边要执行SM2加密，但是实在不行了，就不加密，android有加密
            try await _ = AiNetManager.shared.requestPush(jsonString: toJson(bean) ?? "", modeType: String.self)
        }
    }
    
    //删除定时任务
    func deletSchedule(msgId: String) async throws {
        let bean =  DeleteSchedulesBean()
        bean.msgId = msgId
        try await _ = AiNetManager.shared.deletePush(jsonString: toJson(bean) ?? "", modeType: String.self)
    }
    
}
